function filterMenu(result: Menu[], menus: Menu[]) {
  function appendMenu(result: Menu[], menu: Menu) {
    const alreadyMenu = result.find(item => item.path === menu.path)
    if (alreadyMenu) {
      // 合并显隐控制
      if (!menu.hideInMenu) {
        alreadyMenu.hideInMenu = false
      }
      if (!menu.hideChildrenInMenu) {
        alreadyMenu.hideChildrenInMenu = false
      }

      // 合并元素权限
      Object.keys({...alreadyMenu.elementAuth, ...menu.elementAuth})
      .forEach(key => {
        alreadyMenu.elementAuth[key] = alreadyMenu.elementAuth[key] || !!menu.elementAuth[key]
      })

      // 合并子菜单
      if (alreadyMenu.children && menu.children) {
        filterMenu(alreadyMenu.children, menu.children)
      } else if (menu.children) {
        alreadyMenu.children = menu.children
      }
    } else {
      result.push(menu)
    }
  }

  // 合并菜单
  menus.forEach(item => {
    appendMenu(result, item)
  })
}

function mergeMenus(roles: Role[]) {
  const result: Menu[] = []
  roles.forEach(item => {
    filterMenu(result, item.menus)
  })
  return result
}

function getMenus(user: User) {
  const { roles } = user
  const menus: Menu[] = mergeMenus(roles || [])
  return menus
}

export default getMenus
